package com.lcq.study.test.demo;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonView;
import com.lcq.study.test.demo.annotation.AesResponseBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @ClassName AesResponseBodyAdvice
 * @Description
 * @Author lichuanqi
 * @Date 2022/9/24 17:30
 * @Version 1.0
 **/
@ControllerAdvice
@Slf4j
public class AesResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Value("${xk.aes-key}")
    private String aesKey;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.hasMethodAnnotation(AesResponseBody.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        RequestMapping mapping = returnType.getMethodAnnotation(RequestMapping.class);
        String[] value = mapping.value();
        String url = String.join(",", value);
        log.info("url:{}", url);

        return AesUtils.encrypt(JSON.toJSONString(body), aesKey);
    }


}
